package com.hoangkien.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.hoangkien.activity.widget.IPopupWindow;
import com.hoangkien.adapter.SettingAdapter;
import com.hoangkien.config.CKSharePreferences;
import com.hoangkien.config.ColoringKidsConfig;
import com.hoangkien.fingerpaint.DrawView;
import com.mango.hoangkien.coloringkids.R;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class DrawBitmapActivity extends Activity implements OnClickListener{
	private static final String TAG = "FingerPaint";
	DrawView drawView;
	ImageView ivSave;
	ImageView ivSetting;
	
	private IPopupWindow popupSortby;
	
    /** Called when the activity is first created. */
    @SuppressLint("NewApi") @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(getResources().getConfiguration().orientation);
        drawView = new DrawView(this);
        setContentView(drawView);
        drawView.setBackgroundColor(Color.WHITE);
        drawView.changeColour(7);//mau den
        drawView.requestFocus();
        
        //custom actionbar trong android.
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getActionBar().setDisplayShowTitleEnabled(false);
        getActionBar().setDisplayShowHomeEnabled(false);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        View actionBarView = getLayoutInflater().inflate(R.layout.actionbar_layout, null);
        ActionBar.LayoutParams params = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        actionBar.setCustomView(actionBarView, params);
        ivSave = (ImageView) actionBarView.findViewById(R.id.actionbar_save);
        ivSetting = (ImageView) actionBarView.findViewById(R.id.actionbar_setting);
        ivSave.setOnClickListener(this);
        ivSetting.setOnClickListener(this);
    }
    
    
    void setCustomBackground(DrawView v) {
    	Intent fileChooserIntent = new Intent();
    	fileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
    	fileChooserIntent.setType("image/*");
    	fileChooserIntent.setAction(Intent.ACTION_GET_CONTENT);
    	startActivityForResult(Intent.createChooser(fileChooserIntent, "Select Picture"), 1);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (resultCode == RESULT_OK)
    	{
	    	Uri resultUri = data.getData();
	    	
	    	String drawString = resultUri.getPath();
	    	String galleryString = getGalleryPath(resultUri);
	    	
	    	if (galleryString != null)
	    	{
	    		Log.d(TAG, galleryString);
	    		drawString = galleryString;
	    	}
	    	else
	    	{
	    		Log.d(TAG, drawString);
		    	if (drawString.contains("//"))
		    	{
		    		drawString = drawString.substring(drawString.lastIndexOf("//"));
		    	}
	    	}
	    	
	    	// set the background to the selected picture
	    	if (drawString.length() > 0)
	    	{
	    		Drawable drawBackground = Drawable.createFromPath(drawString);
	    		drawView.setBackgroundDrawable(drawBackground);
	    	}
	    	
    	}
    }
    
    // used when trying to get an image path from the URI returned by the Gallery app
    public String getGalleryPath(Uri uri) {
    	String[] projection = { MediaStore.Images.Media.DATA };
    	Cursor cursor = managedQuery(uri, projection, null, null, null);
    	
    	if (cursor != null) {
    		int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    		cursor.moveToFirst();
    		return cursor.getString(column_index);
    	}
    	
    	
    	return null;
    }
    
    @Override
    public void onBackPressed() {
    	super.onBackPressed();
    	HomekidsActivity.actionLaunch(DrawBitmapActivity.this);
    }
    
    public static Bitmap getBitmapFromView(View view) {
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable =view.getBackground();
        if (bgDrawable!=null) {
        	 bgDrawable.draw(canvas);
        }
        else {
        	canvas.drawColor(Color.WHITE);
        }
        view.draw(canvas);
        return returnedBitmap;
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.actionbar_save:
			Toast.makeText(DrawBitmapActivity.this, "Lưu ảnh!", Toast.LENGTH_SHORT).show();
			Bitmap b = getBitmapFromView(drawView);
			String path = Environment.getExternalStorageDirectory().toString();
			OutputStream fOut = null;
			File file = new File(path, "image" + System.currentTimeMillis()+".jpg");
			try {
				fOut = new FileOutputStream(file);
				b.compress(Bitmap.CompressFormat.PNG, 85, fOut);
				fOut.flush();
				fOut.close();
				MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
				Log.e("DrawBitmapActivity", "save successfully + path = "+path+"/"+file.getName());
				Toast.makeText(DrawBitmapActivity.this, "Lưu ảnh!", Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				Log.e("DrawBitmapActivity", e.toString());
				Toast.makeText(DrawBitmapActivity.this, "Đã có lỗi sảy ra: "+e.toString(), Toast.LENGTH_SHORT).show();
			}
			HomekidsActivity.actionLaunch(DrawBitmapActivity.this);
			break;
		case R.id.actionbar_setting:
			String[] arr = new String[]{"màu sắc","công cụ"};
			getDataSpinner1(arr, ivSetting);
			break;

		default:
			break;
		}
	}
	
	private void getDataSpinner1(final String[] values, final ImageView button) {
		popupSortby = new IPopupWindow(this, R.layout.popup_sortby_layout, null, false, button.getMeasuredWidth(), LayoutParams.WRAP_CONTENT);
		ListView listPopup = (ListView) popupSortby.getView().findViewById(R.id.listPopup);
		if(values != null && values.length != 0){
			Integer[] arrDraw = new Integer[4];
			arrDraw[0] = R.drawable.icon_clear;
			arrDraw[1] = R.drawable.icon_color;
			arrDraw[2] = R.drawable.icon_pen;
			arrDraw[3] = R.drawable.icon_background;
			SettingAdapter adapter = new SettingAdapter(DrawBitmapActivity.this, R.layout.spinner_adapter, arrDraw);
			listPopup.setAdapter(adapter);
		}
		listPopup.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				switch (position) {
				case 0: //clear
					drawView.clearPoints();
					break;
				case 1:  //color
					final Dialog dialog = new Dialog(DrawBitmapActivity.this);
					dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
					dialog.setContentView(R.layout.dialog_color);
					Button btwhite = (Button) dialog.findViewById(R.id.dialog_white);
					btwhite.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_WHITE);
							dialog.dismiss();
						}
					});
					Button btblue = (Button) dialog.findViewById(R.id.dialog_blue);
					btblue.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_BLUE);
							dialog.dismiss();
						}
					});
					Button btLightBlue = (Button) dialog.findViewById(R.id.dialog_light_blue);
					btLightBlue.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_LIGHT_BLUE);
							dialog.dismiss();
						}
					});
					Button btGreen = (Button) dialog.findViewById(R.id.dialog_green);
					btGreen.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_GREEN);
							dialog.dismiss();
						}
					});
					Button btPink = (Button) dialog.findViewById(R.id.dialog_pink);
					btPink.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_PINK);
							dialog.dismiss();
						}
					});
					Button btRed = (Button) dialog.findViewById(R.id.dialog_red);
					btRed.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_RED);
							dialog.dismiss();
						}
					});
					Button btYellow = (Button) dialog.findViewById(R.id.dialog_yellow);
					btYellow.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_YELLOW);
							dialog.dismiss();
						}
					});
					Button btBlack = (Button) dialog.findViewById(R.id.dialog_black);
					btBlack.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_BLACK);
							dialog.dismiss();
						}
					});
					Button btPicture = (Button) dialog.findViewById(R.id.dialog_picture);
					Button btCancel = (Button) dialog.findViewById(R.id.dialog_bt_cancel);
					btPicture.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeColour(ColoringKidsConfig.COLOR_PICTURE);
							dialog.dismiss();
						}
					});
					btCancel.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.dismiss();
						}
					});
					dialog.show();
					break;
				case 2:   //pen width
					final Dialog dialog1 = new Dialog(DrawBitmapActivity.this);
					dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
					dialog1.setContentView(R.layout.dialog_width_pen);
					Button btExtraSmall = (Button) dialog1.findViewById(R.id.dialog_extra_small);
					btExtraSmall.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeWidth(ColoringKidsConfig.PEN_EXTRA_SMALL);
							dialog1.dismiss();
						}
					});
					Button btSmall = (Button) dialog1.findViewById(R.id.dialog_small);
					btSmall.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeWidth(ColoringKidsConfig.PEN_SMALL);
							dialog1.dismiss();
						}
					});
					Button btMedium = (Button) dialog1.findViewById(R.id.dialog_medium);
					btMedium.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeWidth(ColoringKidsConfig.PEN_MEDIUM);
							dialog1.dismiss();
						}
					});
					Button btLarge = (Button) dialog1.findViewById(R.id.dialog_large);
					btLarge.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeWidth(ColoringKidsConfig.PEN_LARGE);
							dialog1.dismiss();
						}
					});
					Button btExtraLarge = (Button) dialog1.findViewById(R.id.dialog_extra_large);
					btExtraLarge.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.changeWidth(ColoringKidsConfig.PEN_EXTRA_LARGE);
							dialog1.dismiss();
						}
					});
					Button btCancelPen = (Button) dialog1.findViewById(R.id.dialog_bt_cancel);
					btCancelPen.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog1.dismiss();
						}
					});
					dialog1.show();
					break;
				case 3:   //background
					final Dialog dialog_background = new Dialog(DrawBitmapActivity.this);
					dialog_background.requestWindowFeature(Window.FEATURE_NO_TITLE);
					dialog_background.setContentView(R.layout.dialog_color);
					Button btwhite_bg = (Button) dialog_background.findViewById(R.id.dialog_white);
					btwhite_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.setBackgroundColor(Color.WHITE);
							dialog_background.dismiss();
						}
					});
					Button btblue_bg = (Button) dialog_background.findViewById(R.id.dialog_blue);
					btblue_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.setBackgroundColor(Color.BLUE);
							dialog_background.dismiss();
						}
					});
					Button btLightBlue_bg = (Button) dialog_background.findViewById(R.id.dialog_light_blue);
					btLightBlue_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.setBackgroundColor(Color.CYAN);
							dialog_background.dismiss();
						}
					});
					Button btGreen_bg = (Button) dialog_background.findViewById(R.id.dialog_green);
					btGreen_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.setBackgroundColor(Color.GREEN);
							dialog_background.dismiss();
						}
					});
					Button btPink_bg = (Button) dialog_background.findViewById(R.id.dialog_pink);
					btPink_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.setBackgroundColor(Color.MAGENTA);
							dialog_background.dismiss();
						}
					});
					Button btRed_bg = (Button) dialog_background.findViewById(R.id.dialog_red);
					btRed_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.setBackgroundColor(Color.RED);
							dialog_background.dismiss();
						}
					});
					Button btYellow_bg = (Button) dialog_background.findViewById(R.id.dialog_yellow);
					btYellow_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.setBackgroundColor(Color.YELLOW);
							dialog_background.dismiss();
						}
					});
					Button btBlack_bg = (Button) dialog_background.findViewById(R.id.dialog_black);
					btBlack_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							drawView.setBackgroundColor(Color.BLACK);
							dialog_background.dismiss();
						}
					});
					Button btPicture_bg = (Button) dialog_background.findViewById(R.id.dialog_picture);
					btPicture_bg.setVisibility(View.INVISIBLE);
					Button btCancel_bg = (Button) dialog_background.findViewById(R.id.dialog_bt_cancel);
					btCancel_bg.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog_background.dismiss();
						}
					});
					dialog_background.show();
					break;

				default:
					break;
				}
				popupSortby.dismiss();
			}
		});
		popupSortby.setAutoHideOutside();
		popupSortby.showAsDropDown(button);
	}

}